#' @title 聚合柱状图带统计检验 #统计图表 #假设检验 #errorbar
#' @description 绘制带有均值柱、蜂群点、标准误误差线和统计检验的聚合柱状图
#' @Eexample
#' 使用示例：
#' set.seed(123)
#' df <- data.frame(
#'   subj_idx = rep(1:20, each = 2),
#'   condition = rep(c("A", "B"), 20),
#'   rt = rnorm(40, mean = c(5, 6), sd = 1)
#' )
#' aggr_bar_with_test(df, x = "condition", dv = "value")

library(dplyr)
library(tidyplots)

load("simulated_data.rdata")

aggr_bar_with_test <- function(data, x, dv, ID = "subject_id", facet = NULL, ...) {
  # 预处理分组变量
  dis <- c(x, facet) %>% Filter(Negate(is.null), .)
  
  # 数据聚合
  long_data <- data %>%
    select(!!!rlang::syms(c(ID, dis, dv))) %>% 
    group_by(!!!rlang::syms(c(ID, dis))) %>%
    summarise(!!dv := mean(.data[[dv]], na.rm = TRUE), .groups = "drop") %>%
    mutate(across(all_of(c(ID, dis)), factor))
  
  # 构建基础图形
  p <- tidyplot(
    data = long_data,
    x = !!rlang::sym(x),
    y = !!rlang::sym(dv),
    color = !!rlang::sym(x),
    ...
  ) %>%
    add_data_points_beeswarm(alpha=0.3) %>%
    add_mean_bar(alpha = 0.4) %>%
    add_sem_errorbar() %>%
    add_mean_value() %>%
    add_test_pvalue(hide_info = TRUE)
  
  # 添加分面处理
  if (!is.null(facet)) {
    p <- p %>% split_plot(by = !!rlang::sym(facet))
  }
  
  return(p)
}

aggr_bar_with_test(df, x = "condition", dv = "rt")
